part of '../shelf.dart';

const String _keySubject = "subject";

/// 确保用户已登录，解码subject，并将主体注入到request的context中
Middleware redeemToken = (Handler inner) => (Request request) {
      // 获取请求中的token信息
      final String? authToken = request.headers['Authorization'];
      if (authToken == null) {
        return response(401, "header中'Authorization'字段为空，请传入token");
      }

      // 尝试解码token，如果解码失误，则返回403错误
      try {
        // 解码token，并获取subject主体
        String subject = TokenKit.redeem(authToken);

        // 将id信息注入到request中，形成新的request
        final newRequest = request.change(context: {_keySubject: subject});

        // 使用handler处理新的request
        return inner(newRequest);
      } on Bug catch (e) {
        return response(401, e);
      }
    };

extension ReadSubject on Request {
  String get subject =>
      context.getField<String>(_keySubject, "在获取subject之前，必须先试用redeemToken中间件");
  int get id => int.parse(subject);
}
